
import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_deer/account/account_router.dart';
import 'package:flutter_deer/account/iview/agent_user_betting_summary_iview.dart';
import 'package:flutter_deer/account/models/agent_user_betting_entity.dart';
import 'package:flutter_deer/account/presenter/agent_user_betting_summary_presenter.dart';
import 'package:flutter_deer/account/provider/agent_betting_record_page_provider.dart';
import 'package:flutter_deer/account/widgets/rise_number_text.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/mvp/power_presenter.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/res/gaps.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/routers/fluro_navigator.dart';
import 'package:flutter_deer/util/image_utils.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/util/theme_utils.dart';
import 'package:flutter_deer/widgets/my_card.dart';
import 'package:flutter_deer/widgets/my_refresh_list.dart';
import 'package:flutter_deer/widgets/state_layout.dart';
import 'package:flutter_deer/widgets/my_app_bar.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:provider/provider.dart';

class AgentBettingRecordPage extends StatefulWidget {

  const AgentBettingRecordPage({super.key});

  @override
  _AgentBettingRecordPageState createState() => _AgentBettingRecordPageState();
}

class _AgentBettingRecordPageState extends State<AgentBettingRecordPage> with BasePageMixin<AgentBettingRecordPage, PowerPresenter>,AutomaticKeepAliveClientMixin<AgentBettingRecordPage> implements AgentUserBettingSummaryIMvpView{

  final GlobalKey _bodyKey = GlobalKey();

  AgentUserBettingSummaryPageProvider provider = AgentUserBettingSummaryPageProvider();
  late AgentUserBettingSummaryPresenter agentUserBettingSummaryPresenter;

  @override
  bool get wantKeepAlive => false;

  @override
  void setSummaryData(AgentUserBettingSummaryPoolEntity? entity){
    provider.setSummaryData(entity);
  }

  @override
  PowerPresenter<dynamic> createPresenter() {
    final PowerPresenter<dynamic> powerPresenter = PowerPresenter<dynamic>(
        this);
    agentUserBettingSummaryPresenter = new AgentUserBettingSummaryPresenter();
    powerPresenter.requestPresenter([agentUserBettingSummaryPresenter]);
    return powerPresenter;
  }

  @override
  void initState() {
    super.initState();
    if(mounted){
      _onRefresh();
    }
  }

  @override
  void dispose() {
    provider.dispose();
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  Future<dynamic> _onRefresh() async {
    Future.delayed(Duration(seconds: 1),()=>{agentUserBettingSummaryPresenter.getAgentUserBettingSummaryData()});
  }

  Future<dynamic> _loadMore() async {
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    final Color? iconColor = ThemeUtils.getIconColor(context);
    return Scaffold(key: _bodyKey,
        appBar: MyAppBar(centerTitle: '${DeerLocalizations.of(context)!.bettingRecord.nullSafe}'),
    body: ChangeNotifierProvider<AgentUserBettingSummaryPageProvider>(
    create: (_) => provider,
    child:  Consumer<AgentUserBettingSummaryPageProvider>(
    builder: (_,provider,child){
    if(provider.stateType==StateType.loading){
    return StateLayout(type: StateType.loading);
    }
    return DeerListView(
    itemCount: provider.list!.length+1,
    stateType: provider.stateType!,
    onRefresh: _onRefresh,
    loadMore: _loadMore,
    hasMore: false!,
    itemBuilder: (_, index) {
      if(index==0){
        return _buildCard(provider,provider.poolEntity!.totalScore,provider.poolEntity!.totalBettingTimes);
      }
      AgentUserBettingSummaryEntity item = provider.list!.elementAt(index-1);
      return GestureDetector(
        onTap: (){
          AgentUserBettingParamEntity paramEntity = AgentUserBettingParamEntity();
          paramEntity.accountId = item.accountId;
          paramEntity.username = item.username;
          NavigatorUtils.push(context, AccountRouter.agentUserBettingPersonPage,arguments:paramEntity);
        },
        child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 10.0,vertical: 5),
            child: MyCard(
                child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 5),
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Gaps.vGap5,
                          Row(
                              children: [
                                CircleAvatar(radius: 24.0,backgroundColor: Colors.transparent,backgroundImage: ImageUtils.getImageProvider(Constant.imageServerHost+'${item!.userAvatar}', holderImg: 'shop/tx')),
                                Gaps.hGap8,
                                Text('${DeerLocalizations.of(context)!.playerAccount.nullSafe}:${item!.accountId}')
                              ]
                          ),
                          Gaps.vGap8,
                          Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                Text('${DeerLocalizations.of(context)!.totalBettingAmount.nullSafe}:${item!.totalBettingScore}'),
                                Text('${DeerLocalizations.of(context)!.totalWinningAmount}:${item.totalWinScore}'),
                              ]
                          ),
                          Gaps.vGap8,
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text('${DeerLocalizations.of(context)!.bettingTimes.nullSafe}:${item.totalBettingTimes}'),
                              Text('${DeerLocalizations.of(context)!.bettingTime.nullSafe}:${item!.lastBettingTimeStr}')
                            ],
                          ),
                          Gaps.vGap5
                        ]
                    )
                ))
        )
      );
    }
    );
    }
    )));
  }

  Widget _buildCard(AgentUserBettingSummaryPageProvider provider,double? totalScore,int? totalTimes) {
    return AspectRatio(
        aspectRatio: 2.55,
        child: Container(
            margin: const EdgeInsets.symmetric(horizontal: 6.0),
            padding: const EdgeInsets.all(6.0),
            decoration: BoxDecoration(
              image: DecorationImage(
                image: ImageUtils.getAssetImage('account/bg'),
                fit: BoxFit.fill,
              ),
            ),
            child: provider.stateType==StateType.loading?Row(
                children: <Widget>[
                  _TotalBettingStatistics(title: '${DeerLocalizations.of(context)!.totalBettingAmount.nullSafe}', count: '0.00',countFormat:'double'),
                  _TotalBettingStatistics(title: '${DeerLocalizations.of(context)!.bettingTimes.nullSafe}', count: '0',countFormat:'int'),
                ]
            ):Row(
                children: <Widget>[
                  _TotalBettingStatistics(title: '${DeerLocalizations.of(context)!.totalBettingAmount.nullSafe}', count: '${totalScore}',countFormat:'double'),
                  _TotalBettingStatistics(title: '${DeerLocalizations.of(context)!.bettingTimes.nullSafe}', count: '${totalTimes}',countFormat:'int'),
                ]
            )
        )
    );
  }

}

class _TotalBettingStatistics extends StatelessWidget {

  const _TotalBettingStatistics({
    required this.title,
    required this.count,
    required this.countFormat,
    this.alignment,
    this.moneyTextStyle
  });

  final String title;
  final String count;
  final String countFormat;
  final MainAxisAlignment? alignment;
  final TextStyle? moneyTextStyle;

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: MergeSemantics(
        child: Column(
          mainAxisAlignment: alignment ?? MainAxisAlignment.center,
          children: <Widget>[
            /// 横向撑开Column，扩大语义区域
            const SizedBox(width: double.infinity),
            Text(title, style: const TextStyle(color: Colours.text_disabled, fontSize: Dimens.font_sp14)),
            Gaps.vGap8,
            countFormat=='double'?
            RiseNumberText(
                NumUtil.getDoubleByValueStr(count) ?? 0,
                style: moneyTextStyle ?? const TextStyle(
                    color: Colours.text_disabled,
                    fontSize: Dimens.font_sp14,
                    fontWeight: FontWeight.bold,
                    fontFamily: 'RobotoThin'
                )
            ):Text(count,style: moneyTextStyle ?? const TextStyle(
                color: Colours.text_disabled,
                fontSize: Dimens.font_sp14,
                fontWeight: FontWeight.bold,
                fontFamily: 'RobotoThin'
            )
            )
          ],
        ),
      ),
    );
  }
}